<?php
/**
 * Created by PhpStorm.
 * User: 王松
 * Time: 2017/12/15 09:23
 */

namespace App\Project\Search;

use App\Project\Search\Translate\AuxiliaryTranslate;
use App\Project\Search\Translate\PastTranslate;
use App\Project\Search\Translate\PhysicalTranslate;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;

class Translate
{
    protected $result;

    /**
     * @var array
     */
    protected $translates = [
        'aux'      => AuxiliaryTranslate::class,
        'past'     => PastTranslate::class,
        'physical' => PhysicalTranslate::class,
    ];

    /**
     * @var array
     */
    protected $instance = [];

    protected $rules = [];

    /**
     * Translate constructor.
     * @param \Illuminate\Support\Collection $result
     */
    public function __construct(Collection $result)
    {
        $this->result = $result;

        foreach ($this->translates as $key => $translate) {
            $this->translates[$key] = new $translate();
        }
    }

    /**
     * @return \Illuminate\Support\Collection
     */
    public function getResult()
    {
        $final = collect();
        $wants = collect(request()->input())->filter(function ($query, $key) {
            return isset($query['select']) && !empty($query);
        })->keys();

        $this->result->map(function (Model $result) use ($final, $wants) {
            $id = $result->id . Str::random(5);
            $final->put($id, []);

            collect($result->toArray())->map(function ($attribute, $key) use ($final, $wants, $id) {
                $keys = explode('-', $key);

                if (count($keys) > 1) {
                    foreach ($wants as $want) {
                        if ($key == explode('_', $want, 2)[0]) {
                            list($class, $method) = explode('-', $want);
                            $final[$id] = array_merge($final[$id],
                                [$want => $this->translates($class, $method, $attribute)]);
                        }
                    }
                } else {
                    $final[$id] = array_merge($final[$id], [$key => $attribute]);
                }
            });
        });

        return $final;
    }

    public function translates($class, $method, $value)
    {
        if (!array_key_exists($class, $this->translates)) {
            return $value;
        }

        $class = $this->translates[$class];

        $method = Str::camel($method);

        if (method_exists($class, $method)) {
            return $class->$method($value);
        }

        return $value;
    }
}